<?php

namespace app\manystore\controller;

use app\admin\model\User;
use app\common\controller\ManystoreBase;
use fast\Random;
use think\Db;
use think\Exception;
use think\Validate;

/**
 * 家长信息
 *
 * @icon fa fa-circle-o
 */
class Parents extends ManystoreBase
{

    /**
     * Parents模型对象
     * @var \app\manystore\model\Parents
     */
    protected $model = null;
    protected $userModel = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\manystore\model\Parents;
        $this->userModel = new User();

    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $where1 = [];
            $student_id = $this->request->get('student_id');
            $parent_id = Db::name('manystore_parent_student')->where(['student_id' => $student_id])->value('parent_id');

            if (isset($parent_id)) $where1['id'] = ['in',$parent_id];

            $list = $this->model
                    ->where($where1)
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','name','image','createtime']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {

            $params = $this->request->post("row/a");
            $user = $this->request->post("user/a");

            if ($user) {
                if (!Validate::is($user['password'], '\S{6,16}')) {
                    $this->error(__("Please input correct password"));
                }
                db()->startTrans();
                try{

                    $user['salt'] = Random::alnum();
                    $user['password'] = md5(md5($user['password']) . $user['salt']);
                    $user['is_teacher'] = 0;
                    $user['avatar'] = $params['image'];

                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->userModel));

                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                    $result = $this->userModel->validate($validate)->save($user);

                    if ($result === false) {
                        $this->error($this->userModel->getError());
                    }

                    $params['user_id'] = $this->userModel->id;
                    $params['shop_id'] = $this->auth->shop_id;
                    $info = $this->model->save($params);
                    if($info === false){
                        $this->error($this->model->getError());
                    }

                    db()->commit();
                    $this->success();
                }catch (Exception $e){
                    db()->rollback();
                    $this->error($e->getMessage());
                }

            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $user_info = $this->userModel->get(array('id'=>$row['user_id']));
        if(!$user_info){
            $this->error(__('账号资料不存在'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $user = $this->request->post("user/a");

            if ($params) {

                if ($user['password']) {
                    if (!Validate::is($params['password'], '\S{6,16}')) {
                        $this->error(__("Please input correct password"));
                    }
                    $user['salt'] = Random::alnum();
                    $user['password'] = md5(md5($user['password']) . $user['salt']);
                } else {
                    unset($user['password'], $user['salt']);
                }

                $user['avatar'] = $params['image'];
                $result = $user_info->save($user);
                if($result === false){
                    $this->error(__("修改账号资料失败"));
                }

                $result = $row->save($params);

                if ($result === false) {
                    $this->error($row->getError());
                }

                $this->success();
            }
            $this->error();
        }
        $grouplist = $this->auth->getGroups($row['id']);
        $groupids = [];
        foreach ($grouplist as $k => $v) {
            $groupids[] = $v['id'];
        }
        $this->view->assign("row", $row);
        $this->view->assign("user", $user_info);
        $this->view->assign("groupids", $groupids);
        return $this->view->fetch();
    }

    public function selectpage1()
    {
        $value = $this->request->request("keyValue");
        $model = new \app\admin\model\manystore\ParentStudent;

        $arr = $model->getRelationList();
        $list = [];
        $info = [];
        foreach ($arr as $k => $v) {
            if($value == $k) {
                $info = [
                    'id' => $k,
                    'name' => $v
                ];
            }
            $list[] = [
                'id' => $k,
                'name' => $v
            ];
        }
        foreach ($list as $k => $v) {
            if($value == $v['id']) {
                unset($v);
            }
        }
        if($value) array_unshift($list,$info);
        return json(['list' => $list, 'total' => count($list)]);
    }

    public function selectpage2()
    {
        $value = $this->request->request("keyValue");
        $model = new \app\admin\model\manystore\ParentStudent;
        $arr = $model->getContactList();
        $list = [];
        $info = [];
        foreach ($arr as $k => $v) {
            if($value == $k) {
                $info = [
                    'id' => $k,
                    'name' => $v
                ];
            }
            $list[] = [
                'id' => $k,
                'name' => $v
            ];
        }
        foreach ($list as $k => $v) {
            if($value == $v['id']) {
                unset($v);
            }
        }
        if($value) array_unshift($list,$info);
        return json(['list' => $list, 'total' => count($list)]);
    }
}
